package main

import (
	"DemoTest/draw/data"
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
)

var old_data any

// 处理数据内容
func handle() {
	for {
		m := <-manager.Message
		connect := m.Connect
		info := manager.Connections[m.Connect]
		log.Println("接收到信息：", string(m.marshal()))

		//判断游戏是否为开始，或者是加入
		if !manager.IsPlay && m.Type != START && m.Type != JOIN && m.Type != EDIT {
			//未开始则不能发送信息
			m.Connect.WriteMessage(websocket.TextMessage, R{}.marshal(500, "游戏未开始，不允许发送信息", nil))
			continue
		}

		//对信息类型坐判断
		switch m.Type {

		//开始游戏
		case START:
			log.Println(info.Name, "点击了开始游戏")
			//如果不是第一个则不允许开始游戏
			if manager.Queue[0] != connect {
				connect.WriteMessage(websocket.TextMessage, R{}.marshal(500, "只能第一个玩家才能开始游戏", nil))
				log.Println(info.Name, "不是队列第一人不允许开始游戏")
				break
			}
			//如果队列中玩家人数少于2人则不允许开始游戏
			if len(manager.Queue) < 2 {
				connect.WriteMessage(websocket.TextMessage, R{}.marshal(500, "玩家人数太少，不允许开始游戏！", nil))
				log.Println("当前游戏玩家人数太少了不允许开始游戏")
				break
			}
			//游戏已开始
			if manager.IsPlay {
				connect.WriteMessage(websocket.TextMessage, R{}.marshal(500, "游戏已开始", nil))
				log.Println("当前游戏已经启动不允许重复开始游戏")
				break
			}
			//设置游戏开始,设置第一个key
			manager.IsPlay = true
			manager.CurrentKey = data.GetKey()
			manager.QueueIndex = 0
			WriterMessageToAllClient(R{}.marshal(200, "游戏开始", m))
			//设置队列第一个为主持人
			m.Connect.WriteMessage(websocket.TextMessage, R{}.marshal(200, "恭喜成为主持人", Message{Type: COMPERE, Data: manager.CurrentKey.Marshal()}))
			log.Println(info.Name, "开始了游戏")
			break
		//类型为信息
		case MESSAGE:
			log.Println(info.Name, "发送来了信息：", m.Data)
			messageHandler(m)
			break
		//画板信息
		case DRAW:
			log.Println(info.Name, "发送来了画图数据")
			//数据未发生改变
			if old_data == m.Data {
				break
			}
			WriterMessageToAllClient(R{}.marshal(200, "normal", m))
			break
		//加入队列信息
		case JOIN:
			log.Println(info.Name, "加入了游戏")
			//将当前ws客户端加入队列中
			if !manager.IsPlay {
				manager.Queue = append(manager.Queue, m.Connect)
				info.Index = len(manager.Queue) - 1
				connect.WriteMessage(websocket.TextMessage, R{}.marshal(200, "加入成功", Message{Type: JOINSUCCESS, Data: len(manager.Queue) - 1}))
				//获取所有客户端用户信息
				WriterMessageToAllClient(R{}.marshal(200, "操作成功", Message{Type: INFOS, Data: GetAllClientInfo()}))
				break
			}
			connect.WriteMessage(websocket.TextMessage, R{}.marshal(500, "加入失败，游戏已开始！", nil))
			break
		case EDIT:
			//修改信息,只能修改名字
			n := ClientInfo{}
			marshal, _ := json.Marshal(m.Data)
			json.Unmarshal(marshal, &n)
			log.Println(info.Name, "修改了昵称为 ->", n.Name)
			info.Name = n.Name
			WriterMessageToAllClient(R{}.marshal(200, "操作成功", Message{Type: INFOS, Data: GetAllClientInfo()}))
			break
		default:
			connect.WriteMessage(websocket.TextMessage, R{}.marshal(500, "未知信息", nil))
			break
		}
	}
}

// 类型为message的处理
func messageHandler(m Message) {
	info := manager.Connections[m.Connect]

	log.Println(info.Name, "回答了：", m.Data)
	//错误则正常发送信息
	if m.Data != manager.CurrentKey.Title {
		WriterMessageToAllClient(R{}.marshal(200, "normal", Message{Type: MESSAGE, Data: fmt.Sprint(info.Name, "：", m.Data)}))
		return
	}

	//回答正确，判断此人是否已回答过
	if _, ok := manager.CorrectCount[m.Connect]; ok {
		WriterMessageToAllClient(R{}.marshal(200, "normal", Message{Type: MESSAGE, Data: fmt.Sprint("警告：玩家【", info.Name, "】不能将答案说出！")}))
		return
	}
	//1.回答人数+1
	scope := 0
	if len(manager.CorrectCount) == 0 {
		scope += 3
	} else if len(manager.CorrectCount) < 2 {
		scope += 2
	} else {
		scope += 1
	}
	//2.积分增加
	manager.CorrectCount[m.Connect] = true
	info.Scope += scope
	log.Println(info.Name, "回答正确", " 积分+", scope, " 当前积分：", info.Scope)
	WriterMessageToAllClient(R{}.marshal(200, "normal", Message{Type: MESSAGE, Data: fmt.Sprint(info.Name, " 回答正确 + ", scope)}))
	//回显客户端用户积分
	WriterMessageToAllClient(R{}.marshal(200, "操作成功", Message{Type: INFOS, Data: GetAllClientInfo()}))

	//没有全部回答完毕
	if len(manager.CorrectCount) != len(manager.Queue)-1 {
		return
	}

	//全部回答完毕队列位置+1
	manager.QueueIndex++
	//重置数据
	manager.CorrectCount = make(map[*websocket.Conn]bool)
	log.Println("下一轮游戏开始，换下一位玩家")
	WriterMessageToAllClient(R{}.marshal(200, fmt.Sprint("下一轮游戏"), Message{Type: NEXT, Data: "下一轮游戏"}))
	//清空画图内容
	WriterMessageToAllClient(R{}.marshal(200, "normal", Message{Type: DRAW, Data: []any{}}))

	//判断游戏是否结束
	if len(manager.CorrectCount) >= 2 {
		manager.IsPlay = false
		log.Println("总游戏结束，请重新开始")
		WriterMessageToAllClient(R{}.marshal(200, fmt.Sprint("游戏结束"), Message{Type: GAMEOVER, Data: "游戏结束"}))
		return
	}

	//给主持人发送信息
	if manager.QueueIndex >= len(manager.Queue) {
		//如果当前索引越界了就设置为0然后给循环次数+1
		manager.QueueIndex = 0
		manager.CurrentCount++
	}
	//更新key
	manager.CurrentKey = data.GetKey()
	manager.Queue[manager.QueueIndex].WriteMessage(websocket.TextMessage, R{}.marshal(200, "恭喜成为主持人", Message{Type: COMPERE, Data: manager.CurrentKey.Marshal()}))
}

// GetAllClientInfo 获取所有端的信息
func GetAllClientInfo() []ClientInfo {
	defer func() {
		if err := recover(); err != nil {
			log.Println(err)
		}
	}()
	infos := make([]ClientInfo, 0)
	for _, v := range manager.Queue {
		info := manager.Connections[v]
		infos = append(infos, *info)
	}
	return infos
}

// WriterMessageToAllClient 将数据写回各个端
func WriterMessageToAllClient(data []byte) {
	for conn := range manager.Connections {
		conn.WriteMessage(websocket.TextMessage, data)
	}
}
